package com.yulang.security.core.config;

import com.yulang.security.core.handler.CustomAuthenticationFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import java.io.IOException;

@Component
public class MyExpiredSessionStrategy implements SessionInformationExpiredStrategy {


    @Autowired
    private CustomAuthenticationFailHandler failHandler;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        UserDetails principal = (UserDetails) event.getSessionInformation().getPrincipal();
        System.out.println(principal.getUsername());
        AuthenticationException exception =
                new AuthenticationServiceException(principal.getUsername()+"在其他地方登录");
        try {
            event.getRequest().setAttribute("toAuth",true);
            failHandler.onAuthenticationFailure(event.getRequest(),event.getResponse(),exception);
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
}
